<template>
  <div class="dashboard-container">


    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">校园智慧竞赛平台 - 管理后台</h1>
      </div>
      <div class="header-right">
        <span class="admin-name">{{ adminName }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>
    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" @click="navigateTo('/dashboard')">
            <i class="icon">📊</i>
            <span>仪表盘</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-audit')">
            <i class="icon">👥</i>
            <span>用户审核</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-management')">
            <i class="icon">👤</i>
            <span>用户管理</span>
          </div>
          <div class="menu-item active">
            <i class="icon">⚡</i>
            <span>队伍管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/homepage-editor')">
            <i class="icon">🏠</i>
            <span>主页编辑</span>
          </div>
          <div class="menu-item" @click="navigateTo('/system-notifications')">
            <i class="icon">📢</i>
            <span>通知管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/news-management')">
            <i class="icon">📰</i>
            <span>新闻管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/event-management')">
            <i class="icon">🏆</i>
            <span>赛事管理</span>
          </div>
        </nav>

      </aside>

      <!-- 主要内容区域 -->
      <main class="content">
        <div class="page-header">
          <h2>队伍管理</h2>
          <div class="header-actions">
            <div class="search-box">
              <input v-model="searchKeyword" type="text" placeholder="搜索队伍名称或编号" class="search-input"
                @keyup.enter="handleSearch" />
              <button class="search-btn" @click="handleSearch">搜索</button>
            </div>
          </div>
        </div>

        <!-- 状态说明 -->
        <div class="status-info">
          <div class="info-icon">ℹ️</div>
          <div class="info-text">
            <strong>数据说明：</strong>以下为所有队伍数据，点击队伍可查看详情
          </div>
        </div>

        <!-- 队伍列表 -->
        <div class="team-list">
          <div v-if="loading" class="loading">
            加载中...
          </div>

          <div v-else-if="currentTeams.length === 0" class="empty-state">
            <div class="empty-icon">⚡</div>
            <p>{{ searchKeyword ? '未找到匹配的队伍' : '暂无队伍数据' }}</p>
          </div>

          <div v-else class="team-table">
            <table>
              <thead>
                <tr>
                  
                  <th>队伍编号</th>
                  <th>队伍名称</th>
              
         
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="team in currentTeams" :key="team.teamId" class="team-row clickable-row"
                  @click="viewTeamDetail(team)" title="点击查看详情">
                  <td class="team-code">{{ team.teamCode || '未分配' }}</td>
                  <td class="team-name">{{ team.teamName || '未命名队伍' }}</td>
              
    
                  <td class="create-time">{{ formatTime(team.createTime) }}</td>
                  <td>
                    <div class="team-actions" @click.stop>
                      <button class="view-btn" @click.stop="viewTeamDetail(team)">
                        查看详情
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1">
          <button class="page-btn" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button class="page-btn" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
            下一页
          </button>
        </div>
      </main>
    </div>

    <!-- 队伍详情弹窗 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>队伍详情</h3>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-content" v-if="selectedTeam">
            <!-- 队伍基本信息 -->
            <div class="detail-section">
              <h4>队伍基本信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>队伍名称：</label>
                  <span>{{ selectedTeam.teamName || '未命名队伍' }}</span>
                </div>
                <div class="detail-item">
                  <label>队伍编号：</label>
                  <span>{{ selectedTeam.teamCode || '未分配' }}</span>
                </div>
                <div class="detail-item">
                  <label>队伍类型：</label>
                  <span>{{ selectedTeam.teamType || '未分类' }}</span>
                </div>
                <div class="detail-item">
                  <label>队员人数：</label>
                  <span>{{ selectedTeam.currentMembers || 0 }} / {{ selectedTeam.maxMembers || 0 }}</span>
                </div>
                <div class="detail-item">
                  <label>队伍状态：</label>
                  <span class="team-status" :class="selectedTeam.status === 1 ? 'active' : 'inactive'">
                    {{ selectedTeam.status === 1 ? '活跃' : '非活跃' }}
                  </span>
                </div>
                <div class="detail-item">
                  <label>创建时间：</label>
                  <span>{{ formatTime(selectedTeam.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <label>最后更新：</label>
                  <span>{{ formatTime(selectedTeam.updateTime) }}</span>
                </div>
              </div>
            </div>

            <!-- 队伍介绍 -->
            <div class="detail-section" v-if="selectedTeam.teamIntro">
              <h4>队伍介绍</h4>
              <div class="team-intro">
                {{ selectedTeam.teamIntro }}
              </div>
            </div>

            <!-- 指导老师信息 -->
            <div class="detail-section" v-if="selectedTeam.instructor">
              <h4>指导老师</h4>
              <div class="instructor-info">
                <div class="instructor-card">
                  <div class="instructor-avatar">
                    <img v-if="selectedTeam.instructor.avatar" :src="selectedTeam.instructor.avatar"
                      :alt="selectedTeam.instructor.realName" />
                    <div v-else class="avatar-placeholder">
                      {{ selectedTeam.instructor.realName ? selectedTeam.instructor.realName.charAt(0) : '师' }}
                    </div>
                  </div>
                  <div class="instructor-details">
                    <div class="instructor-name">{{ selectedTeam.instructor.realName || '未知' }}</div>
                    <div class="instructor-title">{{ selectedTeam.instructor.professionalTitle || '教师' }}</div>
                    <div class="instructor-contact-info">
                      <span class="instructor-id">工号：{{ selectedTeam.instructor.employeeId || '未知' }}</span>
                      <span class="instructor-contact" v-if="selectedTeam.instructor.email">邮箱：{{ selectedTeam.instructor.email }}</span>
                      <span class="instructor-phone" v-if="selectedTeam.instructor.phone">电话：{{ selectedTeam.instructor.phone }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 队员信息 -->
            <div class="detail-section" v-if="selectedTeam.members && selectedTeam.members.length > 0">
              <h4>队员信息 ({{ selectedTeam.members.length }}人)</h4>
              <div class="members-list">
                <div v-for="member in selectedTeam.members" :key="member.id" class="member-card">
                  <div class="member-avatar">
                    <img v-if="member.avatar" :src="member.avatar" :alt="member.realName" />
                    <div v-else class="avatar-placeholder">
                      {{ member.realName ? member.realName.charAt(0) : '?' }}
                    </div>
                  </div>
                  <div class="member-info">
                    <div class="member-name">{{ member.realName || '未知' }}</div>
                    <div class="member-details">
                      <span class="member-id">学号：{{ member.studentNumber || '未知' }}</span>
                      <span class="member-role" v-if="member.memberRole">角色：{{ member.memberRole }}</span>
                      <span class="member-college" v-if="member.college">学院：{{ member.college }}</span>
                    </div>
                    <div class="member-score">
                      <span class="score-label">分数：</span>
                      <span class="score-value" :class="getScoreClass(member.score)" v-if="member.score !== null && member.score !== undefined">{{ member.score }}</span>
                      <span class="score-value no-score" v-else>暂无评分</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 入驻专家信息 -->
            <div class="detail-section" v-if="selectedTeam.experts && selectedTeam.experts.length > 0">
              <h4>入驻专家 ({{ selectedTeam.experts.length }}人)</h4>
              <div class="experts-list">
                <div v-for="expert in selectedTeam.experts" :key="expert.id" class="expert-card">
                  <div class="expert-avatar">
                    <img v-if="expert.avatar" :src="expert.avatar" :alt="expert.realName" />
                    <div v-else class="avatar-placeholder">
                      {{ expert.realName ? expert.realName.charAt(0) : '专' }}
                    </div>
                  </div>
                  <div class="expert-info">
                    <div class="expert-name">{{ expert.realName || '未知专家' }}</div>
                    <div class="expert-title">{{ expert.professionalTitle || '专家' }}</div>
                    <div class="expert-details">
                      <span class="expert-id">工号：{{ expert.employeeId || '未知' }}</span>
                      <span class="expert-contact" v-if="expert.email">邮箱：{{ expert.email }}</span>
                      <span class="expert-phone" v-if="expert.phone">电话：{{ expert.phone }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 比赛信息 -->
            <div class="detail-section" v-if="selectedTeam.currentCompetition">
              <h4>当前比赛</h4>
              <div class="competition-info">
                {{ selectedTeam.currentCompetition }}
              </div>
            </div>

            <!-- 获奖信息 -->
            <div class="detail-section" v-if="selectedTeam.awardInfo">
              <h4>获奖信息</h4>
              <div class="award-info">
                {{ selectedTeam.awardInfo }}
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { ElMessage } from 'element-plus'
import {
  getTeamListService,
  getTeamDetailService,
  searchTeamsService
} from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = 10

// 队伍数据
const teams = ref([])

// 当前显示的队伍列表
const currentTeams = computed(() => {
  // 实现前端分页
  const startIndex = (currentPage.value - 1) * pageSize
  const endIndex = startIndex + pageSize
  const pagedTeams = teams.value.slice(startIndex, endIndex)

  console.log(`分页信息 - 当前页: ${currentPage.value}, 每页: ${pageSize}, 总数据: ${teams.value.length}, 显示: ${pagedTeams.length}条 (${startIndex + 1}-${Math.min(endIndex, teams.value.length)})`)

  return pagedTeams
})

// 弹窗状态
const showDetailModal = ref(false)
const selectedTeam = ref(null)

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 搜索处理
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，重新加载数据
    currentPage.value = 1
    loadTeamData()
    return
  }

  loading.value = true
  try {
    console.log('搜索队伍，关键词:', searchKeyword.value.trim())
    const result = await searchTeamsService(searchKeyword.value.trim())
    console.log('搜索API返回:', result)
    
    if (result.code === 200) {
      // 后端可能返回单个对象或数组，需要适配
      let teamData = result.data || []
      if (!Array.isArray(teamData)) {
        teamData = [teamData]
      }
      
      teams.value = teamData
      // 计算总页数
      totalPages.value = Math.ceil(teams.value.length / pageSize)
      currentPage.value = 1
      console.log(`搜索完成，找到 ${teams.value.length} 支队伍`)
    } else {
      console.error('搜索失败:', result)
      ElMessage.error(result.msg || result.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error(`搜索失败: ${error.message || '网络错误'}`)
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '未知'
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 获取分数样式
const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 60) return 'pass'
  return 'fail'
}

// 加载队伍数据
const loadTeamData = async () => {
  loading.value = true
  try {
    console.log('开始获取队伍列表...')
    const result = await getTeamListService()
    console.log('队伍列表API返回:', result)
    
    if (result.code === 200) {
      // 后端可能返回单个对象或数组，需要适配
      let teamData = result.data || []
      if (!Array.isArray(teamData)) {
        // 如果返回的是单个队伍对象，转换为数组
        teamData = [teamData]
      }
      
      teams.value = teamData
      // 计算总页数
      totalPages.value = Math.ceil(teams.value.length / pageSize)
      console.log(`队伍数据加载成功，共 ${teams.value.length} 支队伍:`, teams.value)
      
      if (teams.value.length === 0) {
        console.warn('没有获取到队伍数据，可能是数据库为空或接口问题')
      }
    } else {
      console.error('获取队伍列表失败:', result)
      ElMessage.error(result.msg || result.message || '获取队伍列表失败')
    }
  } catch (error) {
    console.error('加载队伍数据失败:', error)
    ElMessage.error(`加载队伍数据失败: ${error.message || '网络错误'}`)
  } finally {
    loading.value = false
  }
}

// 查看队伍详情
const viewTeamDetail = async (team) => {
  try {
    console.log('获取队伍详情，teamId:', team.teamId)
    // 获取完整的队伍详情
    const result = await getTeamDetailService(team.teamId)
    console.log('队伍详情API返回:', result)
    if (result.code === 200) {
      selectedTeam.value = result.data
      console.log('队伍详情数据:', selectedTeam.value)
      console.log('队员信息:', selectedTeam.value?.members)
      console.log('专家信息:', selectedTeam.value?.experts)
      showDetailModal.value = true
    } else {
      console.error('获取队伍详情失败:', result)
      ElMessage.error(result.msg || result.message || '获取队伍详情失败')
    }
  } catch (error) {
    console.error('获取队伍详情失败:', error)
    ElMessage.error(`获取队伍详情失败: ${error.message || '网络错误'}`)
  }
}

// 关闭弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedTeam.value = null
}

// 切换页面
const changePage = (page) => {
  currentPage.value = page
  // 不需要重新加载数据，因为使用前端分页
  // currentTeams计算属性会自动更新显示的数据
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadTeamData()
})
</script>

<style scoped>
@import '@/assets/css/UserAudit.css';

/* 队伍管理特有样式 */
.team-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 400px;
}

.team-table table {
  width: 100%;
  border-collapse: collapse;
}

.team-table th,
.team-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.team-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
}

.team-row {
  transition: all 0.3s ease;
  cursor: pointer;
}

.team-row:hover {
  background: #f0f8ff;
}

.clickable-row {
  cursor: pointer;
}

.team-name {
  font-weight: 500;
  color: #1890ff;
}

.team-code {
  font-family: 'Courier New', monospace;
  color: #666;
}

.count-badge {
  background: #1890ff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.count-badge.expert {
  background: #52c41a;
}

.team-actions {
  display: flex;
  gap: 8px;
}

.view-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.3s ease;
}

.view-btn:hover {
  background: #40a9ff;
}

/* 详情弹窗样式 */
.modal-content.large {
  max-width: 900px;
  width: 90%;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  max-height: calc(90vh - 120px);
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-section:last-child {
  border-bottom: none;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.team-intro,
.competition-info,
.award-info {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  line-height: 1.6;
  color: #333;
}

/* 指导老师卡片 */
.instructor-card {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.instructor-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.instructor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: #1890ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
}

.instructor-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.instructor-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.instructor-contact {
  color: #999;
  font-size: 12px;
}

/* 队员列表 */
.members-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.member-card {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.member-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.member-avatar .avatar-placeholder {
  font-size: 14px;
}

.member-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.member-details {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.member-details span {
  display: block;
  margin-bottom: 2px;
}

.member-score {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.score-label {
  color: #666;
}

.score-value {
  font-weight: 600;
  padding: 1px 6px;
  border-radius: 4px;
}

.score-value.excellent {
  background: #f6ffed;
  color: #52c41a;
}

.score-value.good {
  background: #fff7e6;
  color: #faad14;
}

.score-value.pass {
  background: #e6f7ff;
  color: #1890ff;
}

.score-value.fail {
  background: #fff2f0;
  color: #ff4d4f;
}

.score-value.no-score {
  background: #f5f5f5;
  color: #999;
}

.team-status.active {
  color: #52c41a;
  font-weight: 500;
}

.team-status.inactive {
  color: #ff4d4f;
  font-weight: 500;
}

.instructor-contact-info,
.expert-details {
  font-size: 12px;
  color: #666;
}

.instructor-contact-info span,
.expert-details span {
  display: block;
  margin-bottom: 2px;
}

/* 专家列表 */
.experts-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

.expert-card {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f0f8ff;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #d6e4ff;
}

.expert-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.expert-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.expert-avatar .avatar-placeholder {
  font-size: 14px;
  background: #52c41a;
}

.expert-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.expert-title {
  color: #1890ff;
  font-size: 12px;
  margin-bottom: 4px;
}

.expert-contact {
  color: #999;
  font-size: 11px;
}

/* 状态信息样式 */
.status-info {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-icon {
  font-size: 16px;
}

.info-text {
  color: #0050b3;
  font-size: 14px;
}
</style>